package com.kaiwukj.android.ufamily.app;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavigationCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ProcessUtils;
import com.blankj.utilcode.util.Utils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.kaiwukj.android.mcas.base.BaseApplication;
import com.kaiwukj.android.mcas.integration.AppManager;
import com.kaiwukj.android.ufamily.BuildConfig;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.app.constant.SPParam;
import com.kaiwukj.android.ufamily.hx.DemoHelper;
import com.kaiwukj.android.ufamily.hx.UserCacheManager;
import com.kaiwukj.android.ufamily.mvp.helper.AccountStore;
import com.kaiwukj.android.ufamily.mvp.helper.AppStore;
import com.kaiwukj.android.ufamily.mvp.helper.TokenStore;
import com.kaiwukj.android.ufamily.mvp.http.api.ApiRespCode;
import com.kaiwukj.android.ufamily.mvp.http.api.service.AccountService;
import com.kaiwukj.android.ufamily.mvp.http.api.service.KeeperService;
import com.kaiwukj.android.ufamily.mvp.http.callback.ApiCallBack;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.KeeperEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.TokenInvalidEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.UpdateUserInfoEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.KeeperResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserResult;
import com.kaiwukj.android.ufamily.mvp.http.exception.ApiException;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;
import com.kaiwukj.android.ufamily.mvp.ui.page.account.login.vcode.LoginVCodeIndexActivity;
import com.kaiwukj.android.ufamily.mvp.ui.widget.RefreshLayout;
import com.kaiwukj.android.ufamily.utils.SPUtils;
import com.kaiwukj.android.ufamily.utils.ServiceHistoryStore;
import com.meituan.android.walle.WalleChannelReader;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.BuglyLog;
import com.tencent.bugly.crashreport.CrashReport;
import com.videogo.openapi.EZOpenSDK;
import com.zghl.mclient.client.ZghlMClient;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jaaksi.pickerview.picker.BasePicker;
import org.jaaksi.pickerview.util.Util;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import timber.log.Timber;

public class MyApplication extends BaseApplication {

    private int storeId;
    private int sysCommunityId;

    private static MyApplication instance;

    private Disposable delayDisposable;

    public boolean isFirst = false;

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        Utils.init(this);
        LogUtils.getConfig().setLogSwitch(BuildConfig.DEBUG || Constant.isDev);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        AccountStore.init();
        initDefaultPicker();
        //initHX();
        delayDisposable = Observable.timer(800, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    initBugly();
                    initJPush();
                    initEZ();
                    EventBus.getDefault().register(this);
                    if (TokenStore.isLogin()) {
                        requestUserInfo(0);
                    }
                });

        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            throwable.printStackTrace();
            // 抓取到异常时，立即重启应用
            restartApp(MyApplication.this);
        });
    }

    public static void restartApp(Context context) {
        final Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(intent);
            System.exit(0);
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        EventBus.getDefault().unregister(this);
        instance = null;
        if (delayDisposable != null && !delayDisposable.isDisposed()) {
            delayDisposable.dispose();
        }
    }

    public int getStoreId() {
        return storeId;
    }

    public void setStoreId(int storeId) {
        this.storeId = storeId;
    }

    public String getToken() {
        return AppStore.getToken();
    }

    public int getSysCommunityId() {
        return getCommunityId();
    }

    public int getCommunityId() {
        return getUserInfo().getLastCommunityId();
    }

    /**
     * 使用之前判空
     *
     * @return
     */
    public UserResult getUserInfo() {
        return AccountStore.getUserResult();
    }

    public void setUserInfo(UserResult userInfo) {
        AccountStore.updateUserCache(userInfo);
    }

    public void updateKeeperInfo(KeeperResult result) {
        UserResult userResult = getUserInfo();
        if (result == null) {
            userResult.setHkeeperId(-1);
            userResult.setKeeperHxName("");
            userResult.setKeeperPhone("");
            EventBus.getDefault().post(new KeeperEvent(KeeperEvent.UPDATE, ""));
        } else {
            userResult.setHkeeperId(result.getHousekeeperId());
            userResult.setKeeperHxName(result.getHxName());
            userResult.setKeeperPhone(result.getPhone());
            EventBus.getDefault().post(new KeeperEvent(KeeperEvent.UPDATE, userResult.getKeeperHxName()));
        }
        setUserInfo(userResult);
    }


    @Subscribe
    public void onGetUserInfoEvent(UpdateUserInfoEvent event) {
        if (event.getCode() == UpdateUserInfoEvent.REQUEST) {
            requestUserInfo(1);
        }
    }

    private void requestUserInfo(int way) {

        getAppComponent().repositoryManager().obtainRetrofitService(AccountService.class)
                .getUserInfo()
                .compose(RxUtils.schedulerHelper())
                .compose(RxUtils.handleResult())
                .subscribe(new ApiCallBack<UserResult>() {
                    @Override
                    public void onSuccess(@NonNull UserResult result) {
                        AccountStore.updateUserCache(result);
                        if (way != 0) {
                            loginHX(result);
                        }
                        requestKeeper();
                        EventBus.getDefault().post(new UpdateUserInfoEvent(UpdateUserInfoEvent.RESP_OK));
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        e.printStackTrace();
                        EventBus.getDefault().post(new UpdateUserInfoEvent(UpdateUserInfoEvent.RESP_FAILED));
                    }
                });
    }

    private void requestKeeper() {
        getAppComponent().repositoryManager().obtainRetrofitService(KeeperService.class)
                .getMyKeeper()
                .compose(RxUtils.handleResult())
                .compose(RxUtils.schedulerHelper())
                .subscribe(new ApiCallBack<KeeperResult>() {
                    @Override
                    public void onSuccess(@NonNull KeeperResult result) {
                        updateKeeperInfo(result);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (e instanceof ApiException) {
                            if (((ApiException) e).getErrCode() == ApiRespCode.KEEPER_UNBIND) {
                                updateKeeperInfo(null);
                            }
                        }
                    }
                });
    }

    private void initJPush() {
        //极光推送
        JPushInterface.setDebugMode(true);
        JPushInterface.init(getApplicationContext());
        JPushInterface.setChannel(getApplicationContext(), getChannel());
    }

    //萤石
    private void initEZ() {
        //sdk日志开关，正式发布需要去掉
        // EZOpenSDK.showSDKLog(true);
        //设置是否支持P2P取流,详见api
        EZOpenSDK.enableP2P(true);
        /* APP_KEY请替换成自己申请的 */
        EZOpenSDK.initLib(this, "44c6f8196ebd45a8a7f988ab994a1a61");
    }

    private void initBugly() {
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
        String processName = ProcessUtils.getCurrentProcessName();
        strategy.setAppChannel(getChannel());
        strategy.setAppVersion(AppUtils.getAppVersionName());
        strategy.setAppPackageName(AppUtils.getAppPackageName());
        strategy.setUploadProcess(processName == null || processName.equals(getPackageName()));
        strategy.setBuglyLogUpload(true);
        BuglyLog.setCache(12 * 1000);

        //CrashReport.initCrashReport(getApplicationContext(), "ac60cb09be", Constant.isDev, strategy);
        Bugly.init(getApplicationContext(), "ac60cb09be", Constant.isDev, strategy);
    }

    public String getChannel() {
        if (Constant.isDev) {
            return "test";
        }
        String channel = WalleChannelReader.getChannel(getApplicationContext());
        if (TextUtils.isEmpty(channel)) {
            return "d_kaiwu";
        }
        return channel;
    }

    //上架时是否审核金融资质
    public boolean isCheckMoney() {
        return "xiaomi".equals(getChannel());
    }

    static {
        //设置全局的Header构建器
        RefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> new ClassicsHeader(context));
        //设置全局的Footer构建器
        RefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //指定为经典Footer，默认是 BallPulseFooter
            //layout.set
            return new ClassicsFooter(context);
        });
    }

    private void initDefaultPicker() {
        // 利用修改静态默认属性值，快速定制一套满足自己app样式需求的Picker.
        // BasePickerView
        PickerView.sDefaultVisibleItemCount = 3;
        PickerView.sDefaultItemSize = 50;
        PickerView.sDefaultIsCirculation = true;

        // PickerView
        PickerView.sOutTextSize = 18;
        PickerView.sCenterTextSize = 18;
        PickerView.sCenterColor = Color.BLACK;
        PickerView.sOutColor = Color.GRAY;

        // BasePicker
        int padding = Util.dip2px(this, 20);
        BasePicker.sDefaultPaddingRect = new Rect(padding, padding, padding, padding);
        BasePicker.sDefaultPickerBackgroundColor = Color.WHITE;
        // 自定义弹窗
     /*   BasePicker.sDefaultDialogCreator = new IGlobalDialogCreator() {
            @Override
            public IPickerDialog create(Context context) {
                return new PickerDialog();
            }
        };*/

        // DefaultCenterDecoration
        DefaultCenterDecoration.sDefaultLineWidth = 1;
        DefaultCenterDecoration.sDefaultLineColor = Color.BLACK;
        //DefaultCenterDecoration.sDefaultDrawable = new ColorDrawable(Color.WHITE);
        int leftMargin = Util.dip2px(this, 10);
        int topMargin = Util.dip2px(this, 2);
        DefaultCenterDecoration.sDefaultMarginRect =
                new Rect(leftMargin, -topMargin, leftMargin, -topMargin);
    }

    private void loginHX(UserResult result) {
        if (EMClient.getInstance().isLoggedInBefore()) {
            LogUtils.i("已登录聊天服务器");
            return;
        }
        if (result == null || result.getHxName() == null) return;
        EMClient.getInstance().login(result.getHxName().toLowerCase(), "jyl2020", new EMCallBack() {
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Timber.e("登录聊天服务器成功！");
                SPUtils.getInstance().put(SPParam.HX_USER_ID, result.getHxName().toLowerCase());
                SPUtils.getInstance().put(SPParam.HX_USER_NICK_NAME, result.getNickName());
                SPUtils.getInstance().put(SPParam.HX_HEAD_IMAGE, result.getHeadImg());
                LogUtils.e("--------------登录聊天服务器成功-----------");
                updateHxUser(result);
            }

            @Override
            public void onError(int code, String error) {
                LogUtils.e("--------------登录聊天服务器失败-----------" + code + ":" + error);
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });

    }

    private void updateHxUser(UserResult result) {
        try {
            UserCacheManager.save(result.getId(), result.getHxName().toLowerCase(), result.getNickName(), result.getHeadImg());
            DemoHelper.getInstance().getUserProfileManager().updateCurrentUserNickName(result.getNickName());
            DemoHelper.getInstance().getUserProfileManager().setCurrentUserAvatar(result.getHeadImg());
            DemoHelper.getInstance().setCurrentUserName(result.getHxName().toLowerCase()); // 环
        } catch (Exception e) {
            LogUtils.e("聊天用户信息更新失败");
        }
    }


    @Subscribe(sticky = true)
    public void onTokenInvalidEvent(TokenInvalidEvent tokenInvalidEvent) {
        /*Intent intent = new Intent();
        intent.setClass(this, LoginIndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);*/
        ARouter.getInstance().build(ARouterUrlKt.CodeLoginRouterUrl)
                //.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK)
                .navigation(this, new NavigationCallback() {
                    @Override
                    public void onFound(Postcard postcard) {

                    }

                    @Override
                    public void onLost(Postcard postcard) {

                    }

                    @Override
                    public void onArrival(Postcard postcard) {
                        EMClient.getInstance().logout(true);
                        ZghlMClient.getInstance().logout();
                        ServiceHistoryStore.clear();
                        AppManager.getAppManager().killAll(LoginVCodeIndexActivity.class);
                    }

                    @Override
                    public void onInterrupt(Postcard postcard) {

                    }
                });

    }

}
